/**
 * Created by zhangqingxi on 2017-04-25.
 */
var modelPath=ROOT_PATH+'/environmental/solidWaste/storageDispose/';

var disposeData;
var outsourcingUnitData;
var exportingCountryData;



//数量验证 本次处理的贮存不能大于实际剩余贮存
$.extend($.fn.validatebox.defaults.rules, {
    lessThan: {
        validator: function(value,param){
            return value <= $(param[0]).val();
        },
        message: '本次处理的贮存不能大于实际剩余贮存'
    }
});



/**
 * 加载处理处理方法
 */
function loadDisposeMethodData(){
    $.ajax({
        url: dictionaryByCode+dictionaryDisposeMethod,
        type:'POST',
        dataType:'json',
        async:false,
        success: function (data) {
            disposeData=data;
        }
    });
}
/**
 * 加载外委单位数据
 */
function loadOutsourcingUnit() {
    $.ajax({
        url: findOu,
        type:'POST',
        dataType:'json',
        async:false,
        success: function (data) {
            outsourcingUnitData=data;
        }
    });
}
/**
 * 加载出口国
 */
function loadExportingCountry() {
    $.ajax({
        url: dictionaryByCode+dictionaryExportingCountry,
        type:'POST',
        dataType:'json',
        async:false,
        success: function (data) {
            exportingCountryData=data;
        }
    });
}

/**
 * 处理方法格式化
 * @param value
 * @param rowData
 * @param rowIndex
 */
function disposeMethodFormatter(value, rowData, rowIndex) {

    for (var i = 0; i < disposeData.length; i++) {
        if (disposeData[i].id == value) {
            return disposeData[i].text;
        }
    }
}
/**
 * 格式化外委单位
 * @param value
 * @param rowData
 * @param rowInde
 */
function outsourcingUnitFormatter(value, rowData, rowInde) {
    for (var i = 0; i < outsourcingUnitData.length; i++) {
        if (outsourcingUnitData[i].id == value) {
            return outsourcingUnitData[i].text;
        }
    }
}
/**
 * 格式化出口国
 * @param value
 * @param rowData
 * @param rowIndex
 */
function exportingCountryFormatter(value, rowData, rowIndex) {

    for (var i = 0; i < exportingCountryData.length; i++) {
        if (exportingCountryData[i].id == value) {
            return exportingCountryData[i].text;
        }
    }
}
/**
 * 计算处理数量
 */
function calculationStorageDisposeNumber(id) {
    //获得处理数量
    var number=0;
    var $selectRow=$(id).datagrid('getRows');
    for(var i=0;i<$selectRow.length;i++){
        number+=parseFloat($selectRow[i].number);
    }
    return number;

}
function getDisposeNumber() {
    //获得处理数量
    var unitDisposeNumber=calculationStorageDisposeNumber('#unitDisposeList');
    var entrustDisposeNumber=calculationStorageDisposeNumber('#entrustDisposeList');
    var exitDisposeNumber=calculationStorageDisposeNumber('#exitDisposeList');
    var number=(unitDisposeNumber+entrustDisposeNumber+exitDisposeNumber).toFixed(2);
    $('#storageDisposeNumber').textbox('setValue',number);

}
/**
 * 获得单元格内元素的行号
 * @param thisObj
 * @returns {*|jQuery}
 */
function getRowIndex(thisObj) {
    return $(thisObj).parent().parent().parent().attr('datagrid-row-index');
}
/**
 * 删除当前行
 * @param id
 */
function deleteRowByRowIndex(id,thisObj) {
    var rowIndex=getRowIndex(thisObj);
    $('#'+id).datagrid('deleteRow',rowIndex);
    getDisposeNumber();
}
/**
 * 编辑当前行
 * @param id
 */
function editRowByRowIndex(id,thisObj) {
    var rowIndex=getRowIndex(thisObj);
    $('#'+id).datagrid('beginEdit',rowIndex);
    $('#endEdit_'+id+'_'+rowIndex).show();
    $('#startEdit_'+id+'_'+rowIndex).hide();
}
/**
 * 结束编辑当前行
 * @param id
 */
function endRowByRowIndex(id,thisObj) {
    var $id=$('#'+id);
    var rowIndex=getRowIndex(thisObj);
    if($id.datagrid('validateRow',rowIndex)){
        $id.datagrid('endEdit',rowIndex);
        $('#startEdit_'+id+'_'+rowIndex).show();
        $('#endEdit_'+id+'_'+rowIndex).hide();
    }else{
        layer.msg('表格没通过验证');
    }
}
/**
 * 加载内部处理表格
 */
function  loadUnitDisposeList() {
    var swaId=$('#swaId').val();
    var url=findUnitDisposeBySwaId+swaId;

    $('#unitDisposeList').datagrid({
        url:url,
        method:'get',
        title:'处理方式-单位内部设施处置利用',
        fitColumns:true,
       // rownumbers:true,
        singleSelect:true,
        striped:true,
        fit:true,
        columns:[[
            {field:'id',title:'操作',width:10,formatter:function (value,row,index) {
                var html='<a href="javascript:void(0)" onclick="deleteRowByRowIndex(\'unitDisposeList\',this)">删除</a>';
                html+='&nbsp;&nbsp;&nbsp;&nbsp;';
                html+='<a href="javascript:void(0)" id="startEdit_unitDisposeList_'+index+'" onclick="editRowByRowIndex(\'unitDisposeList\',this)">编辑</a>';
                html+='<a href="javascript:void(0)" id="endEdit_unitDisposeList_'+index+'" style="display:none" onclick="endRowByRowIndex(\'unitDisposeList\',this)">结束编辑</a>';
                return html;
            }},
            {field:'startDate',title:'处理开始日期',width:10,
                editor:{
                    type:'datebox',
                    options: {
                        editable: false,
                        required: true
                    }
                }
            },
            {field:'endDate',title:'处理结束日期',width:10,
                editor:{
                    type:'datebox',
                    options: {
                        editable: false,
                        required: true
                    }
                }
            },
            {field:'method',title:'处理方法',width:10,
                editor:{
                    type:'combobox',
                    options: {
                        required: true,
                        editable: false,
                        valueField:'id',
                        textField:'text',
                        data:disposeData
                    }
                },
                formatter:disposeMethodFormatter
            },
            {field:'number',title:'处理数量',width:10,
                editor:{
                    type:'numberspinner',
                    options: {
                        required: true,
                        precision:2,
                        min:0
                    }
                }
            }
        ]],
        toolbar: '#unitDisposeToolbar',
        onEndEdit:getDisposeNumber
    });
}
/**
 * 加载外委单位处理表格
 */
function  loadEntrustDisposeList() {
    var swaId=$('#swaId').val();
    var url=findEntrustDisposeBySwaId+swaId;
    $('#entrustDisposeList').datagrid({
        url:url,
        title:'处理方式-提供或委托处理利用',
        fitColumns:true,
       // rownumbers:true,
        singleSelect:true,
        striped:true,
        fit:true,
        columns:[[
            {field:'id',title:'操作',width:10,formatter:function (value,row,index) {
                var html='<a href="javascript:void(0)" onclick="deleteRowByRowIndex(\'entrustDisposeList\',this)">删除</a>';
                html+='&nbsp;&nbsp;&nbsp;&nbsp;';
                html+='<a href="javascript:void(0)" id="startEdit_entrustDisposeList_'+index+'" onclick="editRowByRowIndex(\'entrustDisposeList\',this)">编辑</a>';
                html+='<a href="javascript:void(0)" id="endEdit_entrustDisposeList_'+index+'" style="display:none"  onclick="endRowByRowIndex(\'entrustDisposeList\',this)">结束编辑</a>';
                return html;
            }},
            {field:'startDate',title:'处理开始日期',width:10,
                editor:{
                    type:'datebox',
                    options: {
                        editable: false,
                        required: true
                    }
                }
            },
            {field:'endDate',title:'处理结束日期',width:10,
                editor:{
                    type:'datebox',
                    options: {
                        editable: false,
                        required: true
                    }
                }
            },
            {field:'outsourcingUnitId',title:'外委单位',width:10,
                editor:{
                    type:'combobox',
                    options: {
                        required: true,
                        editable: false,
                        valueField:'id',
                        textField:'text',
                        data:outsourcingUnitData
                    }
                },
                formatter:outsourcingUnitFormatter
            },
            {field:'number',title:'处理数量',width:10,
                editor:{
                    type:'numberspinner',
                    options: {
                        required: true,
                        precision:2,
                        min:0
                    }
                }
            }
        ]],
        toolbar: '#entrustDisposeToolbar',
        onEndEdit:getDisposeNumber
    });
}
/**
 * 加载出口处理表格
 */
function  loadExitDisposeList() {
    var swaId=$('#swaId').val();
    var url=findExitDisposeBySwaId+swaId;
    $('#exitDisposeList').datagrid({
        url:url,
        title:'处理方式-出口',
        fitColumns:true,
       // rownumbers:true,
        singleSelect:true,
        striped:true,
        fit:true,
        columns:[[
            {field:'id',title:'操作',width:10,formatter:function (value,row,index) {
                var html='<a href="javascript:void(0)" onclick="deleteRowByRowIndex(\'exitDisposeList\',this)">删除</a>';
                html+='&nbsp;&nbsp;&nbsp;&nbsp;';
                html+='<a href="javascript:void(0)" id="startEdit_exitDisposeList_'+index+'" onclick="editRowByRowIndex(\'exitDisposeList\',this)">编辑</a>';
                html+='<a href="javascript:void(0)" id="endEdit_exitDisposeList_'+index+'" style="display:none"  onclick="endRowByRowIndex(\'exitDisposeList\',this)">结束编辑</a>';
                return html;
            }},
            {field:'startDate',title:'处理日期',width:10,
                editor:{
                    type:'datebox',
                    options: {
                        editable: false,
                        required: true
                    }
                }
            },
            {field:'exportingCountry',title:'出口国',width:10,
                editor:{
                    type:'combobox',
                    options: {
                        required: true,
                        editable: false,
                        valueField:'id',
                        textField:'text',
                        data:exportingCountryData
                    }
                },
                formatter:exportingCountryFormatter
            },
            {field:'number',title:'出口数量',width:10,
                editor:{
                    type:'numberspinner',
                    options: {
                        required: true,
                        precision:2,
                        min:0
                    }
                }
            }
        ]],
        toolbar: '#exitDisposeToolbar',
        onEndEdit:getDisposeNumber
    });
}
//初始化固废类型
function initSolidWasteType() {

    $('#solidWasteTypeId').combobox({
        data:[{"id":0,"text":"一般"},{"id":1,"text":"危废"}],
        valueField:'id',
        textField:'text',
        panelHeight:'auto',
        editable:false,
        required:true,
        onChange:function (newValue,oldValue) {
            $('#solidWasteId').combobox({
                value:''
            });
            $('#hazardousWasteCodeId').combogrid({
                value:''
            });
            $('#hazardousWasteContent').textbox('setValue','');
            $('#currentStorageNumber').numberspinner('setValue',0);
            var required=false;
            if(newValue==1){
                required=true;
            }
            initSolidWaste(newValue,required);
            resetCombogrid('#hazardousWasteCodeId')
        }
    });
}

//初始化固废名称solidWasteId
function initSolidWaste(solidWasteTypeId,required) {
    $('#solidWasteId').combobox({
        url: solidWasteByTypeId+solidWasteTypeId,
        valueField:'id',
        textField:'text',
        required:true,
        prompt:'请选择',
        editable:false,
        onChange:function (newValue,oldValue) {
            $('#hazardousWasteCodeId').combogrid({
                value:''
            });
            $('#hazardousWasteContent').textbox('setValue','');
            $('#currentStorageNumber').numberspinner('setValue',0);
            if(required){
                findSolidWasteById(newValue);
            }else{
                getStorageDisposeNumber(newValue,null);
            }
        }
    });
}

function findSolidWasteById(id) {
    $.ajax({
        url: solidWasteById+id,
        type:'POST',
        dataType:'json',
        success: function (data) {
            var hazardousWasteTypeId=data.hazardousWasteTypeId;
            initHazardousWasteCode(hazardousWasteTypeId);
        }
    });
}

//初始化危废代码 hazardousWasteCodeId
function initHazardousWasteCode(hazardousWasteTypeId) {
    $('#hazardousWasteCodeId').combogrid({
        required:true,
        editable:false,
        readonly:false,
        panelWidth:500,
        prompt:'请选择',
        idField:'id',
        textField:'code',
        queryParams:{
            sort:'d.addTime',
            order:'desc',
            hazardousWasteTypeId:hazardousWasteTypeId
        },
        fitColumns:true,
        pagination:true,
        rownumbers:true,
        singleSelect:true,
        sortOrder:true,
        striped:true,
        url:hazardousWasteCodeByParam,
        columns:[[
            {field:'code',title:'危废代码',width:60},
            {field:'remarks',title:'危废描述',width:100}
        ]],
        onSelect:function (index, row) {
            $('#hazardousWasteContent').textbox('setValue',row.remarks);
            //获得固废名称
            var solidWasteId=$('#solidWasteId').combobox('getValue');
            getStorageDisposeNumber(solidWasteId,row.id)
        }
    });
}
//根据固废名称和危废代码查询贮存数量
function getStorageDisposeNumber(solidWasteId,hazardousWasteCodeId) {

    $.ajax({
        url: findStorageDisposeNumber,
        data:{
            solidWasteId:solidWasteId,
            hazardousWasteCodeId:hazardousWasteCodeId
        },
        type:'POST',
       // dataType:'json',
        success: function (data) {
            var currentStorageNumber=0;
            if(data!==''){
                var dataResult=$.parseJSON(data);
                currentStorageNumber=dataResult.currentStorageNumber;
            }
            $('#currentStorageNumber').numberspinner('setValue',currentStorageNumber);
        }
    });
}
//固废类型加载之后的事件
function solidWasteTypeLoadSuccess() {

    var required=false;
    var $solidWasteTypeIdValue=$('#solidWasteTypeId').val();
    if($solidWasteTypeIdValue==1){
        required=true;
    }
    solidWasteLoadSuccess(required);
    initSolidWaste($solidWasteTypeIdValue,required);
    //加载固废类型
    initSolidWasteType();
}
//固废名称加载成功之后的事件
function solidWasteLoadSuccess(required) {
    var $solidWasteIdValue=$('#solidWasteId').val();
    if(required){
        findSolidWasteById($solidWasteIdValue,required);
        hazardousWasteCodeLoadSuccess();
    }else{
        resetCombogrid('#hazardousWasteCodeId');
        getStorageDisposeNumber($solidWasteIdValue,null);
    }
}
//危废代码加载完成之后的事件
function hazardousWasteCodeLoadSuccess() {
    $('#hazardousWasteCodeId').combogrid({
        //加载完成危废代码之后显示描述
        onLoadSuccess:function (index, row) {
            var $gridObj = $('#hazardousWasteCodeId').combogrid('grid');	// 获取数据表格对象
            var $SelectedRow = $gridObj.datagrid('getSelected');	// 获取选择的行
            if($SelectedRow){
                $('#hazardousWasteContent').textbox('setValue',$SelectedRow.remarks);
                //获得固废名称
                var solidWasteId=$('#solidWasteId').combobox('getValue');
                getStorageDisposeNumber(solidWasteId,$SelectedRow.id);
            }
        }
    });

}



//单位内部处理点击事件
function initUnitDisposeAddButton() {
    $('#btn_unitDispose_add').on('click',function () {
        var $unitDisposeList=$('#unitDisposeList');
        $unitDisposeList.datagrid('insertRow',{
            row: {
                id: '',
                startDate: '',
                endDate: '',
                method:'',
                number:'',
                type:1
            }
        });
        //获得总行数
        var rowsLength=$unitDisposeList.datagrid('getRows').length;
        var rowIndex=rowsLength-1;
        $unitDisposeList.datagrid('beginEdit',rowIndex);
        $('#endEdit_unitDisposeList_'+rowIndex).show();
        $('#startEdit_unitDisposeList_'+rowIndex).hide();

    });
}

//外委单位处理点击事件
function initEntrustDisposeAddButton() {
    $('#btn_entrustDispose_add').on('click',function () {
        var $entrustDisposeList=$('#entrustDisposeList');
        $entrustDisposeList.datagrid('insertRow',{
            row: {
                id: '',
                startDate: '',
                endDate: '',
                exportingCountry:'',
                number:'',
                type:1
            }
        });
        //获得总行数
        var rowsLength=$entrustDisposeList.datagrid('getRows').length;
        var rowIndex=rowsLength-1;
        $entrustDisposeList.datagrid('beginEdit',rowIndex);
        $('#endEdit_entrustDisposeList_'+rowIndex).show();
        $('#startEdit_entrustDisposeList_'+rowIndex).hide();

    });
}
function initExitDisposeAddButton() {
    //外委单位处理点击事件
    $('#btn_exitDispose_add').on('click',function () {
        var $exitDisposeList=$('#exitDisposeList');
        $exitDisposeList.datagrid('insertRow',{
            row: {
                id: '',
                startDate: '',
                outsourcingUnitId:'',
                number:'',
                type:1
            }
        });
        //获得总行数
        var rowsLength=$exitDisposeList.datagrid('getRows').length;
        var rowIndex=rowsLength-1;
        $exitDisposeList.datagrid('beginEdit',rowIndex);
        $('#endEdit_exitDisposeList_'+rowIndex).show();
        $('#startEdit_exitDisposeList_'+rowIndex).hide();

    });
}

//表单提交
function initStorageDisposeButtonSave(url) {
    //表单提交
    $('#btn_save').on('click',function () {

        var index=layer.confirm('是否确定保存？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $('#submit_form').form('submit', {
                url:url,
                onSubmit: function (param) {
                    var isValid = $(this).form('validate');
                    if (!isValid) {
                        layer.close(index);
                        layer.msg("请正确填写表单")
                    }
                    //获得单位表格数据
                    var unitDisposeRow=$('#unitDisposeList').datagrid('getRows');
                    param['unitDispose']=JSON.stringify(unitDisposeRow);
                    //获得外委表格数据
                    var entrustDisposeRow=$('#entrustDisposeList').datagrid('getRows');
                    param['entrustDispose']=JSON.stringify(entrustDisposeRow);
                    //获得出口表格数据
                    var exitDisposeRow=$('#exitDisposeList').datagrid('getRows');
                    param['exitDispose']=JSON.stringify(exitDisposeRow);

                    return $(this).form('validate');
                },
                success: function (result) {
                    var data = $.parseJSON(result);
                    successCallback(data)
                }
            });
        });

    });
}
